/**
 * Created by Administrator on 2015/1/11.
 */

var mongoose = require('mongoose');
require('../../expansion/EModel.js');
var User = mongoose.model('User');

var fs = require('fs');

function UserService(){

}

UserService.prototype.getAllUser = function(condition, populate, pages, columns, sort, callback) {
    User.findPagination(condition, populate, pages, columns, sort, callback);
}

/**
 * 获取所有岗位类型
 */
UserService.prototype.getAllProfession = function(callback){
    User.find(null, 'profession', function(err, data){
        var types = [];
        for (var i = 0, len = data.length; i < len; i++) {
            var profession = data[i].profession;
            types.push(profession);
        }
        var types = unique(types);
        callback && callback(err, types);
    });
}

UserService.prototype.uploadUser = function (path, charset, callback) {
    fs.readFile(path, charset || 'utf-8', function(err, content) {
        var users = content.split('\n');
        for(var i= 0,len=users.length;i<len;i++){
            var userArr = users[i].split(',');
            var user = new User();
            user.sid = userArr[0];
            user.name = userArr[1];
            var profession = userArr[2];
            user.profession = profession.replace(/\r|' '/gi, '');
            user.score = 0;
            user.battles = 0;
            user.success = 0;
            user.failure = 0;
            user.flee = 0;
            user.save(function (err) {
                if(err) throw err;
                callback && callback();
            });
        }
        // 删除临时文件
        fs.unlink(path);
    });
}

UserService.prototype.updateUser = function(data, where, callback){
    User.findOneAndUpdate(where, data, function(err, res){
        callback && callback(err, res);
    })
}

module.exports = UserService;

/**
 * 数组去重
 * @param arr
 * @returns {Array}
 */
var unique = function(arr) {
    var ret = []
    var hash = {}

    for (var i = 0; i < arr.length; i++) {
        var item = arr[i]
        var key = typeof(item) + item
        if (hash[key] !== 1) {
            ret.push(item)
            hash[key] = 1
        }
    }
    return ret;
}